var sys = require('sys')
/*
var filename = process.ARGV[2];

if (!filename)
  return sys.puts("Usage: node watcher.js filename");

var spawn = require('child_process').spawn;

var tail = spawn("tail", ["-f", filename]);

// Look at http://nodejs.org/api.html#_child_processes for detail.
//var tail = process.createChildProcess("tail", ["-f", filename]);
sys.puts("start tailing");

tail.stdout.on("output", function (data) {
  sys.puts(data);
});
*/

var fs = require('fs'),
index,
f = "test.txt",
startByte = 0;

fs.stat(f, function(err, stats){
if (err) throw err;
startByte = stats.size;
sys.puts(startByte);
});

/*
fs.watchFile(f, function (curr, prev) {
fs.stat(f, function(err, stats){
if (err) throw err;
fs.createReadStream(f, {
  start: startByte,
  end: stats.size
}).addListener("data", function(lines) {
  //sys.puts(lines);
	index = lines;
  startByte = stats.size;
});
});
});
*/

// From nodejs.org/jsconf.pdf slide 56
var http = require("http");
http.createServer(function(req,res){
  res.writeHeader(200,{"Content-Type": "text/plain"});
  //res.end("Hel");
  //res.end("lo\r\n");
  /*
  tail.stdout.on("output", function (data) {
    res.end("output\r\n");
    res.end(data);
  });*/
  
  fs.stat(f, function(err, stats){
	  if (err) throw err;
	  startByte = stats.size;
	  sys.puts(startByte);
	  });
  
  fs.watchFile(f, function (curr, prev) {
	  fs.stat(f, function(err, stats){
	  if (err) throw err;
	  fs.createReadStream(f, {
	    //start: startByte,
	    //end: stats.size
	  }).addListener("data", function(lines) {
	    //sys.puts(lines);
	  	res.write(lines);
	    //startByte = stats.size;
	  });
	  });
	  });
  
  
  //
  // setTimeout(function () {
  // res.sendBody("World\r\n");
  // res.finish();
  // }, 2000);
}).listen(8000);